local skynet = require "skynet"
local cluster = require "skynet.cluster"
local socket = require "skynet.socket"
local httpd = require "http.httpd"
local sockethelper = require "http.sockethelper"
local urllib = require "http.url"
local table = table
local string = string

local filelog = require "filelog"
local configdao = require "configdao"
local timetool = require "timetool"
local md5 = require "md5"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local platform2login_key = nil

local function response(id, ...)
	local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
	if not ok then
		-- if err == sockethelper.socket_error , that means socket closed.
		skynet.error(string.format("fd = %d, %s", id, err))
	end
end

--处理手机认证
local function handle_authphone(query)
	if not query or query == '' then
		return {}
	end
	
	local tmp = {}
	local q = urllib.parse_query(query)
	if not q or q.phonenum == nil then
		filelog.sys_error("-----------phonenum is nil----------", q)
		return {retcode = -1, retstr = "phonenum is nil"}
	end
	
	--检测手机号格式，11位数字，首位为1
	local phonenum = tostring(q.phonenum) or ""
	local firstch = tonumber(string.sub(phonenum,1,1)) or 0
	if string.len(phonenum) ~= 11 or firstch ~= 1 then
		return {retcode = -1, retstr = "phonenum format is error"}	
	else
		local highbit = tonumber(string.sub(phonenum,1,5)) or -1
		local lowbit = tonumber(string.sub(phonenum,6,11)) or -1
		if highbit == -1 or lowbit == -1 then
			return {retcode = -1, retstr = "phonenum format is error"}
		end
	end

	-- 应该有参数： phonenum, rolename, agencyrid, logintoken
	local tokentime = string.sub(q.logintoken or "", 33) or "0"
	local newtoken = md5.sumhexa((q.phonenum or "") .. tokentime .. platform2login_key) .. tokentime
	if (newtoken ~= q.logintoken) then
		filelog.sys_error("--error token--", newtoken, q, tokentime, platform2login_key)
		return {retcode = -2, retstr = "error token"}
	end

	local status, result = skynet.pcall(cluster.call, "datanode", ".router", "authphone", tostring(q.phonenum), nil, true, nil, tonumber(q.agencyrid), tonumber(q.pkgid))
	if status and result then
		if result[1] == 1 then	--用户已存在
			return {retcode = -3, retstr = "phoennum is signined"}
		else
			tmp = result[2][1]
			tmp.cpass = nil
			tmp.saltpass = nil
			tmp.phonenum = nil
			tmp.phonecpass = nil
			tmp.phonesaltpass = nil
			tmp.guestmobileid = nil
		end
	end

	return tmp
end

skynet.start(function()
	local q = nil --url 解析后的数组
	platform2login_key = configdao.get_cfgsvrs_key("platform2login_key")
	skynet.dispatch("lua", function (_,_,id)
		socket.start(id)
		-- limit request body size to 8192 (you can pass nil to unlimit)
		local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)
		if code then
			if code ~= 200 then
				response(id, code)
			else
				local tmp = {}
				local ok = 0

				local path, query = urllib.parse(url)
				local action = string.sub(path,2) --去掉 / 
				if action == "authwx" and query and query ~= '' then
					ok = 1
				elseif action == "authphone" then
					tmp = handle_authphone(query)
				end
				if ok == 1 then
					q = urllib.parse_query(query)
                    if q and q.unionid == nil then
                        filelog.sys_error("-----------unionid is nil----------", q)
                    end

					-- 应该有参数： unionid, rolename, agencyrid, logintoken
					local tokentime = string.sub(q.logintoken or "", 33) or "0"
					local newtoken = md5.sumhexa((q.unionid or "") .. tokentime .. platform2login_key) .. tokentime
					if(newtoken ~= q.logintoken) then
                        filelog.sys_error("--error token--",newtoken, q.logintoken, "---",q.unionid,"--",tokentime,"--",platform2login_key)
					    ok = 0
					end
				end
				if ok == 1 and q.unionid then
					local status, result
					status, result = skynet.pcall(cluster.call, "datanode", ".router", "authwx", tostring(q.unionid), tostring(q.rolename), tonumber(q.agencyrid), tonumber(q.pkgid))
                    if status and result then 
					    tmp = result[2][1]
					    tmp.cpass = nil
					    tmp.saltpass = nil
                        tmp.phonenum = nil
					    tmp.phonecpass = nil
                        tmp.phonesaltpass = nil
					    tmp.guestmobileid = nil
                    end
				end
				response(id, code, json.encode(tmp))
			end
		else
			if url == sockethelper.socket_error then
				skynet.error("socket closed")
			else
				skynet.error(url)
			end
		end
		socket.close(id)
	end)
end)
